package com.hanbang.taitaigou.utils.http;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;

import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.activity.login.LogInActivity;
import com.hanbang.taitaigou.ui.widget.autoloadding.StatusChangListener;
import com.hanbang.taitaigou.ui.widget.dialog.BaseDialog;
import com.hanbang.taitaigou.utils.other.SharedPreferencesUtils;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.ToastUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.xutils.common.Callback;
import org.xutils.ex.FileLockedException;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.http.app.RequestTracker;
import org.xutils.http.request.UriRequest;

import java.net.SocketException;
import java.net.SocketTimeoutException;

public abstract class HttpCallBack<ResultType> implements Callback.ProgressCallback<ResultType>, RequestTracker {
    private Context context = null;
    private String dialogContent = null;
    private BaseDialog myDialog = null;
    private View[] view;
    private boolean isCancelable = false;
    private SwipeToLoadLayout swipeToLoadLayout;
    private SwipeRefreshLayout swipeRefreshLayout;
    //自动加载刷新
    private StatusChangListener statusChangListener;


    /*
         * 构造函数 参数是准备创建对话框 如果content为null 那么就代表这条http请求不弹出对话框
         */
    public HttpCallBack(Context context, String content) {
        this(context, content, null);
    }

    public HttpCallBack(Context context, String content, View v) {

        this(context, content, null, false, v);
    }

    public HttpCallBack(Context context, String content,
                        boolean isCancelable) {
        this(context, content, null, isCancelable);
    }

    public HttpCallBack(Context context, String content,
                        boolean isCancelable, View v) {

        this(context, content, null, isCancelable, v);
    }

    public HttpCallBack(Context context, String content,
                        SwipeToLoadLayout swipeToLoadLayout) {

        this(context, content, swipeToLoadLayout, false);
    }

    public HttpCallBack(Context context, String content,
                        SwipeToLoadLayout swipeToLoadLayout, View... v) {

        this(context, content, swipeToLoadLayout, false, v);
    }

    public HttpCallBack(Context context, String content,
                        SwipeToLoadLayout swipeToLoadLayout, boolean isCancelable, View... v) {

        this.context = context;
        dialogContent = content;
        this.view = v;
        this.isCancelable = isCancelable;
        this.swipeToLoadLayout = swipeToLoadLayout;
    }

    public HttpCallBack setSwipeRefreshLayout(SwipeRefreshLayout swipeRefreshLayout) {
        this.swipeRefreshLayout = swipeRefreshLayout;
        return this;
    }

    public HttpCallBack setStatusChangListener(StatusChangListener statusChangListener) {
        this.statusChangListener = statusChangListener;
        return this;
    }

    @Override
    public void onStarted() {
        if (view != null) {
            for (int i = 0; i < view.length; i++) {
                View vv = view[i];
                if (vv != null) {
                    vv.setEnabled(false);
                }
            }

        }
        // 判断是否加载对话框
        if (context instanceof Activity) {
            if (!((Activity) context).isFinishing()
                    && UiUtils.isForeground(context)) {
                if (context != null & dialogContent != null) {
                    myDialog = new BaseDialog(context, R.style.base_dialog,
                            BaseDialog.MODE.LOADDING);
                    myDialog.setContent(dialogContent);
                    myDialog.setCancelable(isCancelable);
                    myDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                        }
                    });
                    myDialog.show();
                }
            }
        }
    }

    @Override
    public void onSuccess(ResultType result) {
        LogUtils.e("onSuccess", result.toString());

        /**
         * 判断密码是否错误
         */
        if (result.toString().trim().equals("{\"status\":0, \"msg\":\"获取用户信息失败!\"}")) {
            if (context instanceof BaseActivity) {
                ((BaseActivity) context).passwordIsError(true);
            } else {
                SharedPreferencesUtils.setSharedPreferencesKeyAndValue(context,
                        SharedPreferencesUtils.USER_DATA, "user_id", -1);
                BaseActivity.userData = null;
                /**
                 * 发送登录广播
                 */
                Intent intent = new Intent();
                intent.setAction(LogInActivity.FINISH_FLAG);
                context.sendBroadcast(intent);
            }
        }

    }


    @Override
    public void onError(Throwable error, boolean isOnCallback) {

        if (error != null) {
            LogUtils.e("onFailure->error", error.toString());
        }
        if (!HttpLocalUtils.isNetworkAvailable(context)) {
            ToastUtils.show(context, "请检查网络设置", ToastUtils.LENGTH_SHORT);
        } else if (error instanceof HttpException) { // 网络错误
            HttpException httpEx = (HttpException) error;
            LogUtils.e("onFailure", httpEx.getMessage() + "   code"
                    + httpEx.getCode());
            if (httpEx.getMessage().contains("timed out")) {
                ToastUtils.show(context, "连接超时", ToastUtils.LENGTH_SHORT);
            } else if (httpEx.getCode() == 500) {
                ToastUtils.show(context, "服务器异常", ToastUtils.LENGTH_SHORT);
            } else if (httpEx.getCode() == 0) {
                ToastUtils.show(context, "请求异常", ToastUtils.LENGTH_SHORT);
            } else if (httpEx.getCode() == 403) {
                ToastUtils.show(context, "禁止访问", ToastUtils.LENGTH_SHORT);
            } else {
                //其他错误
                ToastUtils.show(context, "未知网络错误", ToastUtils.LENGTH_SHORT);
            }

        } else if (error instanceof SocketException) {
            //java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)
            //服务器的并发连接数超过了其承载量，服务器会将其中一些连接关闭；
            //如果知道实际连接服务器的并发客户数没有超过服务器的承载量，则有可能是中了病毒或者木马，引起网
            ToastUtils.show(context, "请求过于频繁", ToastUtils.LENGTH_SHORT);
        } else if (error instanceof SocketTimeoutException) {
            //超时
            ToastUtils.show(context, "连接超时", ToastUtils.LENGTH_SHORT);
        } else if (error instanceof FileLockedException) {

        } else {
            //其他错误
            // ToastUtils.show(context, "未知错误", ToastUtils.LENGTH_SHORT);
        }

    }

    @Override
    public void onFinished() {
        if (view != null) {
            for (int i = 0; i < view.length; i++) {
                View vv = view[i];
                if (vv != null) {
                    vv.setEnabled(true);
                }
            }

        }
        if (myDialog != null)

        {
            if (context instanceof Activity) {
                if (!((Activity) context).isFinishing()
                        && UiUtils.isForeground(context)) {
                    myDialog.dismiss();
                }
            }

        }

        if (swipeToLoadLayout != null) {
            if (swipeToLoadLayout.isRefreshing()) {
                swipeToLoadLayout.setRefreshing(false);
            } else if (swipeToLoadLayout.isLoadingMore()) {
                swipeToLoadLayout.setLoadingMore(false);
            }
        }
        if (swipeRefreshLayout != null) {
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
        }
        if(statusChangListener != null){
            statusChangListener.loaddingFinsh();
        }

    }

    @Override
    public void onWaiting() {

    }

    @Override
    public void onLoading(long total, long current, boolean isDownloading) {
        if (isDownloading) {
            LogUtils.e("onLoading", "总长：" + total + "   加载到：" + current);
        }
    }


    @Override
    public void onWaiting(RequestParams var1) {

    }

    @Override
    public void onStart(RequestParams var1) {
        LogUtils.e("onStart", var1.getUri());
    }

    @Override
    public void onCache(UriRequest var1, Object var2) {

    }

    @Override
    public void onCancelled(CancelledException cex) {
    }

    @Override
    public void onFinished(UriRequest request) {

    }

    @Override
    public void onError(UriRequest request, Throwable ex, boolean isCallbackError) {

    }

    @Override
    public final void onSuccess(UriRequest request, Object var2) {

    }

    @Override
    public void onCancelled(UriRequest request) {

    }

    @Override
    public void onRequestCreated(UriRequest uriRequest) {

    }
}
